package com.tange.ai.core.sample.message

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.tange.ai.core.sample.R
import com.tange.ai.core.sample.databinding.ActivityMessageListBinding
import com.tange.base.toolkit.*
import com.tange.base.ui.design.BasicDialogRequest
import com.tange.core.cloud.message.CloudMessage
import com.tange.core.cloud.message.Message
import java.util.Calendar

class MessageListActivity : AppCompatActivity() {

    companion object {
        private const val TAG = "MessageActivity_"
        private const val PARAM_DEVICE_ID = "PARAM_DEVICE_ID"
        private const val VIEW_TYPE_MESSAGE = 0
        private const val VIEW_TYPE_MORE = 1
        private const val PAGE_LIMIT = 10

        fun launch(context: Context, deviceId: String) {
            context.startActivity(Intent(context, MessageListActivity::class.java).apply {
                putExtra(PARAM_DEVICE_ID, deviceId)
            })
        }
    }

    private lateinit var binding: ActivityMessageListBinding
    private lateinit var listAdapter: ListAdapter
    private lateinit var deviceId: String

    private val messagesOfDate: MutableList<Message> = ArrayList()

    private var currentSelectedDate = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        StatusBarUtil.setLightStatusBar(this, true)
        StatusNavUtils.setStatusBarColor(this, ContextCompat.getColor(this, R.color.app_background))
        requestWindowFeature(Window.FEATURE_NO_TITLE)

        deviceId = intent.getStringExtra(PARAM_DEVICE_ID)

        binding = ActivityMessageListBinding.inflate(layoutInflater).apply {
            setContentView(root)
            supportActionBar?.hide()
            root.paddingStatusBar()
        }

        binding.top.left.onClicked { finish() }
        binding.top.right.onClicked { MessageSettingActivity.launch(it.context, deviceId) }

        binding.category.onClicked {
            Tips.show("开发中...")
        }

        binding.date.onClicked {
            if (binding.calendarContainer.isVisible()) {
                binding.calendarContainer.gone()
            } else {
                binding.calendarContainer.visible()
            }
        }

        binding.calendarView.setOnDateChangeListener { _, year, month, dayOfMonth ->
            val day = if (dayOfMonth < 10) "0$dayOfMonth" else "$dayOfMonth"
            val formatMonth = if ((month + 1) < 10) "0${month + 1}" else "${month + 1}"
            val format = "$year-$formatMonth-$day"
            binding.calendarContainer.gone()
            binding.date.setText(format)
            messagesOfDate.clear()
            binding.root.post { queryMessage(format) }
        }

        listAdapter = ListAdapter()
        binding.msgList.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        binding.msgList.adapter = listAdapter

        val initialDate = today()
        binding.date.setText(initialDate)
        queryMessage(initialDate)
        queryCategories()
    }

    private fun queryCategories() {
        CloudMessage.queryMessageCategory {
            // TODO：开发中
        }
    }

    private fun loadMore() {
        queryMessage(currentSelectedDate)
    }

    private fun queryMessage(date: String) {
        currentSelectedDate = date
        binding.loading.visible()
        binding.emptyView.gone()
        CloudMessage.queryMessageByDate(deviceId, date, null, messagesOfDate.size, PAGE_LIMIT) {
            binding.loading.gone()
            if (it.success) {
                it.data?.let {
                    if ((it.total?:0) <= 0 || (it.messages?.size?:0) == 0) {
                        if (messagesOfDate.size == 0) {
                            binding.emptyView.visible()
                            binding.msgList.gone()
                        } else {
                            Tips.show("没有更多数据了")
                        }
                    } else {
                        it.messages?.let {
                            messagesOfDate.addAll(it)
                            listAdapter.refresh(messagesOfDate)
                        }
                        binding.emptyView.gone()
                        binding.msgList.visible()
                    }
                }
            } else {
                Tips.show("请求失败：${it.code}, ${it.message}")
            }
        }
    }

    private fun today(): String {
        val year = Calendar.getInstance().get(Calendar.YEAR)
        val month = Calendar.getInstance().get(Calendar.MONTH)
        val dayOfMonth = Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
        val day = if (dayOfMonth < 10) "0$dayOfMonth" else "$dayOfMonth"
        val formatMonth = if ((month + 1) < 10) "0${month + 1}" else "${month + 1}"
        return "$year-$formatMonth-$day"
    }

    inner class ListAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
        private val messages: MutableList<Message> = java.util.ArrayList()

        fun refresh(list: List<Message>) {
            messages.clear()
            messages.addAll(list)
            notifyDataSetChanged()
        }

        override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            return if (viewType == VIEW_TYPE_MESSAGE) {
                val view: View = LayoutInflater.from(viewGroup.context)
                    .inflate(R.layout.item_message_list, viewGroup, false)
                ViewHolderMessage(view)
            } else {
                val view: View = LayoutInflater.from(viewGroup.context)
                    .inflate(R.layout.item_message_load_more, viewGroup, false)
                ViewHolderLoadMore(view)
            }
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {

            if (holder is ViewHolderMessage) {
                val viewHolderMessage: ViewHolderMessage = holder
                val item = messages[position]
                val messageId = item.id ?: ""
                viewHolderMessage.name.text = item.event?.categoryName ?: ""
                viewHolderMessage.time.text = DateUtil.getStrToTime(item.startTime ?: 0L)

                viewHolderMessage.icon.setColorFilter(Color.WHITE)
                item.event?.categoryIcon?.let {
                    Glide.with(this@MessageListActivity)
                        .load(it)
                        .into(viewHolderMessage.icon)
                }

                item.thumbnail?.let {
                    Glide.with(this@MessageListActivity)
                        .load(it)
                        .error(R.drawable.light_gray_rounded_bg)
                        .apply(RequestOptions.bitmapTransform(RoundedCorners(25)))
                        .into(viewHolderMessage.cover)
                }

                viewHolderMessage.itemView.setOnClickListener {
                    MessageDetailActivity.launch(it.context, deviceId, messageId)
                }

                // 长按删除消息
                viewHolderMessage.itemView.setOnLongClickListener {
                    BasicDialogRequest(it.context).apply {
                        setTitle("你确定要删除此消息吗？")
                        setMessage("删除后不可恢复")
                        setPositiveText("确定")
                        setNegativeText("取消")
                        setNegativeOnClicked { }
                        setPositiveOnClicked {
                            CloudMessage.deleteMessageById(messageId) {
                                if (it.success) {
                                    messages.remove(item)
                                    notifyDataSetChanged()
                                    Tips.show("删除成功")
                                } else {
                                    Tips.show("删除失败 ${it.code}, ${it.message}")
                                }
                            }
                        }
                    }.show()
                    true
                }
            } else if (holder is ViewHolderLoadMore) {
                holder.itemView.setOnClickListener { loadMore() }
            }
        }

        override fun getItemCount(): Int {
            return if (messages.size == 0) 0
            else messages.size + 1
        }

        override fun getItemViewType(position: Int): Int = if (position == (itemCount - 1)) VIEW_TYPE_MORE else VIEW_TYPE_MESSAGE
    }

    class ViewHolderMessage(view: View) : RecyclerView.ViewHolder(view) {
        val icon: ImageView
        val cover: ImageView
        val name: TextView
        val time: TextView

        init {
            icon = view.findViewById(R.id.category_icon)
            cover = view.findViewById(R.id.cover)
            name = view.findViewById(R.id.name)
            time = view.findViewById(R.id.time)
        }
    }

    class ViewHolderLoadMore(view: View) : RecyclerView.ViewHolder(view)
}